package com.zzw.thread.concurrent;

import java.util.Map;
import java.util.concurrent.*;

public class CyclicBarrierTest implements Runnable{

	private CyclicBarrier cyclicBarrier = new CyclicBarrier(4, this);

	private Executor ex = Executors.newFixedThreadPool(4);
	
	private ConcurrentHashMap<String, Integer> count = new ConcurrentHashMap<>();
	
	@Override
	public void run() {
		int result = 0;
		for(Map.Entry<String, Integer> entry:count.entrySet()){
			result += entry.getValue();
		}
		count.put(Thread.currentThread().getName() + "_result", result);
		System.out.println(result);
	}
	
	public void calculate(){
		for(int i = 0;i < 4;i++){
			ex.execute(new Runnable() {
				@Override
				public void run() {
					count.put(Thread.currentThread().getName(), 10);
					try {
						System.out.println(Thread.currentThread().getName() + ":is waiting!");
						cyclicBarrier.await();
						System.out.println(Thread.currentThread().getName() + ":is working!");
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (BrokenBarrierException e) {
						e.printStackTrace();
					}
				}
			});
		}
		ExecutorService.class.cast(ex).shutdown();
	}
	
	public static void main(String[] args) {
		new CyclicBarrierTest().calculate();
	}
}